using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

using UC_Framework;

namespace SwarmPlay
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        UC_LevelManager levelManager;

        bool showBB = true;
        bool showHS = true;

        SpriteFont font1;

        KeyboardState keyState;
        KeyboardState prevKeyState;

        //String dir = @"C:\GPT2011_AI_Swarm_XNA4\SoundExample\Images\";

        Random random;


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            // to be put in game1 constructor after Content.RootDirectory = "Content";
            graphics.PreferredBackBufferHeight = 600;
            graphics.PreferredBackBufferWidth = 800;


        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            LineBatch.init(GraphicsDevice);
            levelManager = new UC_LevelManager();

            levelManager.AddLevel(0, new GameLevel_0());
            levelManager.getLevel(0).InitializeLevel(GraphicsDevice, Content, levelManager);
            levelManager.getLevel(0).LoadContent();
            levelManager.setLevel(0);

            levelManager.AddLevel(1, new GameLevel_1());
            levelManager.getLevel(1).InitializeLevel(GraphicsDevice, Content, levelManager);
            levelManager.getLevel(1).LoadContent();

            levelManager.AddLevel(2, new GameLevel_2());
            levelManager.getLevel(2).InitializeLevel(GraphicsDevice, Content, levelManager);
            levelManager.getLevel(2).LoadContent();

            levelManager.AddLevel(3, new GameLevel_3());
            levelManager.getLevel(3).InitializeLevel(GraphicsDevice, Content, levelManager);
            levelManager.getLevel(3).LoadContent();

            //texBbox = fromFile(dir + "WhiteSquareTrans32.png");

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            levelManager.getCurrentLevel().Update(gameTime);

            keyState = Keyboard.GetState();

            if (keyState.IsKeyDown(Keys.Escape)) this.Exit();


            // TODO: Add your update logic here

            prevKeyState = keyState;

            keyState = Keyboard.GetState();
            if (keyState.IsKeyDown(Keys.Escape)) this.Exit();

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {

            levelManager.getCurrentLevel().Draw(gameTime);
            base.Draw(gameTime);
        }

        // to replace fromfile to be put into Game1 as a method
        public static Texture2D fromFile(String fName, GraphicsDevice gd)
        {
            // note needs :using System.IO;
            Stream fs = new FileStream(fName, FileMode.Open);
            return Texture2D.FromStream(gd, fs);
        }
    }
 
    // *********************************** LimitSound ******************************************************

    /// <summary>
    /// Limits a sound to playing a certian number of instances of itself (stops muddy sound)
    /// </summary>
    public class LimitSound
    {
        SoundEffect se;
        SoundEffectInstance[] sei;
        int numOfSounds;
        int counter;

        /// <summary>
        /// Create it using a soundeffect
        /// </summary>
        /// <param name="soundEffect"></param>
        /// <param name="numOfSoundz"></param>
        public LimitSound(SoundEffect soundEffect, int numOfSoundz)
        {
            numOfSounds = numOfSoundz+1;
            se = soundEffect;
            init();
        }

        /// <summary>
        /// create it using a sound name
        /// </summary>
        /// <param name="name"></param>
        /// <param name="numOfSoundz"></param>
        public LimitSound(string name, int numOfSoundz, ContentManager c)
        {
            se = c.Load<SoundEffect>(name);
            numOfSounds = numOfSoundz+1;
            init();
        }

        private void init()
        {
            counter = 0;
            sei = new SoundEffectInstance[numOfSounds];
            for (int i = 0; i < numOfSounds; i++)
            {
                sei[i] = se.CreateInstance();
            }
        }

        /// <summary>
        /// play the sound from the start
        /// </summary>
        public void playSound()
        {
            sei[counter].Play(); // play it
            counter++;
            if (counter >= numOfSounds) counter = 0;
            sei[counter].Stop(); // stop one for next play
        }

        public void playSoundIfOk()
        {
            // first find one not playing
            for (int i = 0; i < numOfSounds-1; i++)
            {
                if (sei[i].State == SoundState.Stopped)
                {
                    sei[i].Play();
                    return;
                }
            }
        }
    }

}
